package com.blockmeta.bbs.overallserviceapplication.search;

import android.content.Context;
import android.content.Intent;

import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Filterable;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blockmeta.bbs.baselibrary.base.adapter.BaseViewPager;
import com.blockmeta.bbs.baselibrary.net.callback.Callback;
import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.StatusBarUtils;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.gson.GsonUtil;
import com.blockmeta.bbs.baselibrary.widget.tab.SlidingTabLayout;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.business.UmengEvent;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.net.okhttp.OKHttpGetReq;
import com.blockmeta.bbs.overallserviceapplication.R;
import com.blockmeta.bbs.overallserviceapplication.R2;
import com.blockmeta.bbs.overallserviceapplication.mydb.SearchHistorysDao;
import com.blockmeta.bbs.overallserviceapplication.pojo.SearchBannerPOJO;
import com.blockmeta.bbs.overallserviceapplication.pojo.SearchHistoryPOJO;
import com.blockmeta.bbs.overallserviceapplication.search.adapter.SearchHistoryAdapter;
import com.blockmeta.bbs.overallserviceapplication.search.adapter.SearchHotNewAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by author on 2017/12/27.
 */
@Route(path = RouterPath.SEARCH_ACTIVITY)
public class SearchNewActivity extends BaseActivity{

    @BindView(R2.id.search_edit)
    AutoCompleteTextView mSearchEdit;
    @BindView(R2.id.search_cancle)
    TextView mSearchCancle;
    @BindView(R2.id.vp)
    ViewPager mVp;
    @BindView(R2.id.recycler)
    RecyclerView mRecycler;
    @BindView(R2.id.tablayout)
    SlidingTabLayout mTablayout;
    @BindView(R2.id.search_clear)
    RelativeLayout mSearchClear;

    @Autowired(name = Constant.ZERO)
    public String jumpTAG;
    private SearchHistorysDao dao;
    private ArrayList<SearchHistoryPOJO> historyPOJO;
    private ArrayList<SearchHistoryPOJO> limithistoryPOJO;

    private List<View> mViewList;
    private SearchHistoryAdapter historyAdapter;
    private List<String> mTitles;
    private SearchBannerPOJO mBannerPOJO;

    private ArrayAdapter<String> mArrayAdapter;

    private boolean mBlockCompletion = false;

    public String mPreSearch;

    private boolean isClickHistory;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        HashMap<String, String> map = new HashMap<>(2);
        UmengEvent.eventStatistics(mContext, Constant.U_SEARCH, map);
        return LayoutInflater.from(mContext).inflate(R.layout.activity_search_new, null);
    }

    @Override
    public void setStatusBarColor() {
        if (!"night".equals(SharedPreferenceUtil.getString(this, Constant.SKINTYPE, "light"))) {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.status_color);
            StatusBarUtils.setDarkMode(this);
        } else {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.status_red_night);
            StatusBarUtils.setDarkMode(this);
        }
    }

    @Override
    protected void initialize() {
        super.initialize();
        mSearchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mBlockCompletion || mSearchEdit.isPerformingCompletion()) {
                    return;
                }
                getAssociationalWord(s.toString());
                mPreSearch = s.toString();
            }
        });
        mSearchEdit.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String search = ((TextView) view.findViewById(R.id.tv_content)).getText().toString();
                setTextToHistory(search);
            }
        });
        int height = StatusBarUtils.getStatusBarHeight();
        mSearchEdit.setDropDownHeight(mContext.getResources().getDisplayMetrics().heightPixels - height - DimentionsUtil.dp2px(mContext, 35));
        mSearchEdit.setDropDownWidth(mContext.getResources().getDisplayMetrics().widthPixels);
        String[] a = new String[0];
        mArrayAdapter = new ArrayAdapter<String>(mContext, R.layout.item_drop_list, R.id.tv_content, a);
        mSearchEdit.setAdapter(mArrayAdapter);
        OKHttpGetReq okHttpGetReq = new OKHttpGetReq(mContext, NetConstant.SEARCH_BANNER);
        okHttpGetReq.getData(new Callback() {
            @Override
            public void onError(String resp) {

            }

            @Override
            public void onResponse(String resp, int id) {
                try {
                    mBannerPOJO = GsonUtil.buildGson().fromJson(resp, SearchBannerPOJO.class);
                } catch (Exception e) {
                    mBannerPOJO = null;
                }
                if (mBannerPOJO == null || mBannerPOJO.getBanner() == null || mBannerPOJO.getBanner().size() == 0) {
                    return;
                }
                for (int i = 0; i < mBannerPOJO.getBanner().size(); i++) {
                    String type = mBannerPOJO.getBanner().get(i).getType();
                    for (int i1 = 0; i1 < mBannerPOJO.getBanner().get(i).getList().size(); i1++) {
                        mBannerPOJO.getBanner().get(i).getList().get(i1).setType(type);
                    }
                }
                if (!TextUtils.isEmpty(mBannerPOJO.getSubtitles()) && mSearchEdit != null) {
                    String[] split = mBannerPOJO.getSubtitles().split("/");
                    mTitles = Arrays.asList(split);
                    mSearchEdit.setHint(mBannerPOJO.getSubtitles());
                    initTab();
                }
            }
        });
        initDB();
    }

    public void setText(String string) {
        mBlockCompletion = true;
        mSearchEdit.setText(string);
        mSearchEdit.setSelection(string.length());
        mBlockCompletion = false;
    }

    /**
     * 获取联想词
     *
     * @param s 引发联想
     */
    private void getAssociationalWord(final String s) {
        String url = NetConstant.GET_ASSOCIATIONAL_WORD + "?word=" + s;
        OkHttpUtils.get()
                .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, null))
                .url(url)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            String[] strings = new Gson().fromJson(response, String[].class);
                            mArrayAdapter.clear();
                            if (strings != null) {
                                mArrayAdapter.addAll(strings);
                            }
                            ((Filterable) mArrayAdapter).getFilter().filter(s, mSearchEdit);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void initDB() {
        limithistoryPOJO = new ArrayList<>();
        initData();
        dao = new SearchHistorysDao(this);
        historyPOJO = dao.findAll();

        initLitmitList();

        initSearch();


    }

    private void initSearch() {
        mRecycler.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));

        historyAdapter = new SearchHistoryAdapter(R.layout.item_search_history, limithistoryPOJO);
        //点击条目
        historyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (limithistoryPOJO != null) {
                    SearchHistoryPOJO pojo = limithistoryPOJO.get(position);
                    isClickHistory = true;
                    startActivityToResult(pojo.historyword);
                }
            }
        });
        //点击删除
        historyAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                dao.delete(limithistoryPOJO.get(position).historyword);
                limithistoryPOJO.remove(position);
                historyAdapter.notifyDataSetChanged();
                if (limithistoryPOJO.size() == 0) {
                    mSearchClear.setVisibility(View.GONE);
                }

            }
        });

        mRecycler.setAdapter(historyAdapter);
        int itemCount = historyAdapter.getItemCount();
        if (itemCount > 0) {
            mSearchClear.setVisibility(View.VISIBLE);
        } else {
            mSearchClear.setVisibility(View.GONE);
        }

    }


    private void initTab() {
        mViewList = new ArrayList<>();


        View inflate1 = LayoutInflater.from(mContext).inflate(R.layout.item_recy_white, null);
        RecyclerView recy1 = inflate1.findViewById(R.id.item_recy);

        View inflate2 = LayoutInflater.from(mContext).inflate(R.layout.item_recy_white, null);
        RecyclerView recy2 = inflate2.findViewById(R.id.item_recy);

        View inflate3 = LayoutInflater.from(mContext).inflate(R.layout.item_recy_white, null);
        RecyclerView recy3 = inflate3.findViewById(R.id.item_recy);

        View inflate4 = LayoutInflater.from(mContext).inflate(R.layout.item_recy_white, null);
        RecyclerView recy4 = inflate4.findViewById(R.id.item_recy);

        View inflate5 = LayoutInflater.from(mContext).inflate(R.layout.item_recy_white, null);
        RecyclerView recy5 = inflate5.findViewById(R.id.item_recy);


        recy1.setLayoutManager(new GridLayoutManager(mContext, 2, GridLayoutManager.VERTICAL, false));
        recy2.setLayoutManager(new GridLayoutManager(mContext, 2, GridLayoutManager.VERTICAL, false));
        recy3.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        recy4.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        recy5.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));


        SearchHotNewAdapter coinsAdapter = new SearchHotNewAdapter(mBannerPOJO.getBanner().get(0).getList(), mContext);
        recy1.setAdapter(coinsAdapter);

        coinsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                String title = mBannerPOJO.getBanner().get(0).getList().get(position).getTitle();
                startActivityToResult(title, Constant.ZERO);
            }
        });

        SearchHotNewAdapter exchangeAdapter = new SearchHotNewAdapter(mBannerPOJO.getBanner().get(1).getList(), mContext);
        recy2.setAdapter(exchangeAdapter);

        SearchHotNewAdapter newsAdapter = new SearchHotNewAdapter(mBannerPOJO.getBanner().get(2).getList(), mContext);
        recy3.setAdapter(newsAdapter);

        SearchHotNewAdapter bbsAdapter = new SearchHotNewAdapter(mBannerPOJO.getBanner().get(3).getList(), mContext);
        recy4.setAdapter(bbsAdapter);

        SearchHotNewAdapter activeAdapter = new SearchHotNewAdapter(mBannerPOJO.getBanner().get(4).getList(), mContext);
        recy5.setAdapter(activeAdapter);

        View empty = LayoutInflater.from(mContext).inflate(R.layout.empty_data, null);


        if (mBannerPOJO.getBanner().get(0).getList() == null || mBannerPOJO.getBanner().get(0).getList().size() == 0) {
            mViewList.add(empty);
        } else {
            mViewList.add(inflate1);
        }

        if (mBannerPOJO.getBanner().get(1).getList() == null || mBannerPOJO.getBanner().get(1).getList().size() == 0) {
            mViewList.add(empty);
        } else {
            mViewList.add(inflate2);
        }

        if (mBannerPOJO.getBanner().get(2).getList() == null || mBannerPOJO.getBanner().get(2).getList().size() == 0) {
            mViewList.add(empty);
        } else {
            mViewList.add(inflate3);
        }

        if (mBannerPOJO.getBanner().get(3).getList() == null || mBannerPOJO.getBanner().get(3).getList().size() == 0) {
            mViewList.add(empty);
        } else {
            mViewList.add(inflate4);
        }

        if (mBannerPOJO.getBanner().get(4).getList() == null || mBannerPOJO.getBanner().get(4).getList().size() == 0) {
            mViewList.add(empty);
        } else {
            mViewList.add(inflate5);
        }
        BaseViewPager<View> pagerAdapter = new BaseViewPager<>(mViewList, mTitles);

        mVp.setAdapter(pagerAdapter);
        //设置TabLayout和ViewPager绑定
        mTablayout.setViewPager(mVp);
        mTablayout.setCurrentTab(getPositionByJumpTag(jumpTAG,mTitles),false);
    }

    /**
     * 根据收到的tag返回tabLayout应该显示的正确位置
     * @param tag 。
     * @param titles tabs
     * @return position
     */
    private int getPositionByJumpTag(String tag, List<String> titles) {
        int position = 0;
        for (String title : titles) {
            if (tagAdapter(tag).contains(title)){
                return position;
            }
            ++position;
        }
        return 0;
    }

    private String tagAdapter(String tag) {
        if (Constant.SEARCH_FAST.equals(tag)){
            return Constant.SEARCH_NEWS;
        }
        return tag;
    }

    private void initData() {
        mSearchEdit.requestFocus();
        //实现发送按钮的监听
        mSearchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean ableAction = actionId == EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())
                    || actionId == EditorInfo.IME_ACTION_GO;
            if (ableAction) {
                /*隐藏软键盘*/
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(
                    v.getApplicationWindowToken(), 0);
                }
                String editText = mSearchEdit.getText().toString().trim();
                setTextToHistory(editText);
                return true;
            } else {
                return false;
            }
            }
        });
    }

    private void setTextToHistory(String edit_text) {
        //处理输入文本内容
        if (TextUtils.isEmpty(edit_text)) {
            ToastUtil.show(mContext,"搜索关键词不能为空");
        } else {
            //存储到数据库
            dao.addOrUpdate(edit_text);
            historyPOJO.clear();
            historyPOJO.addAll(dao.findAll());
            limithistoryPOJO.clear();
            initLitmitList();
            historyAdapter.notifyDataSetChanged();
            setText("");
            mSearchClear.setVisibility(View.VISIBLE);

            startActivityToResult(edit_text);
        }
    }

    /**
     * 限制搜索长度为10
     */
    private void initLitmitList() {
        if (historyPOJO.size() > 10) {
            for (int i = 0; i < 10; i++) {
                limithistoryPOJO.add(historyPOJO.get(i));
            }
        } else {
            limithistoryPOJO.addAll(historyPOJO);
        }
    }


    @OnClick({R2.id.search_cancle, R2.id.search_clear})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.search_cancle) {
            finish();

        } else if (i == R.id.search_clear) {//提示弹窗
            final RxDialogSureCancel rxDialogEditSureCancel = new RxDialogSureCancel(mContext);
            rxDialogEditSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dao.deleteAll();
                    historyPOJO.clear();
                    limithistoryPOJO.clear();
                    historyAdapter.notifyDataSetChanged();
                    mSearchClear.setVisibility(View.GONE);
                    rxDialogEditSureCancel.cancel();

                }
            });

            rxDialogEditSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    rxDialogEditSureCancel.cancel();
                }
            });
            rxDialogEditSureCancel.show();

        } else {
        }
    }

    /**
     * 需要传递结束数据到SearchCoinsResultActivity
     *
     * @param tv
     */
    private void startActivityToResult(String tv) {
        startActivityToResult(tv,jumpTAG);
    }

    private void startActivityToResult(String tv, String tag) {
        Intent intent = new Intent(mContext, SearchResultActivity.class);
        intent.putExtra(Constant.ZERO, tag);
        intent.putExtra(Constant.SEARCH_COIN, tv);
        if (TextUtils.isEmpty(mPreSearch)) {
            mPreSearch = tv;
        }
        intent.putExtra("word", mPreSearch);
        startActivity(intent);
        finish();
    }
}
